use web_sys::HtmlInputElement;
use yew::prelude::*;

#[derive(Clone, PartialEq, Properties)]
pub struct SliderProps {
    #[prop_or(false)]
    pub disabled: bool,
    #[prop_or(0)]
    pub min: isize,
    #[prop_or(100)]
    pub max: isize,
    #[prop_or(0)]
    pub value: isize,
    #[prop_or_default]
    pub oninput: Callback<isize>,
}

#[function_component]
pub fn Slider(props: &SliderProps) -> Html {
    let oninput = props.oninput.reform(|e: InputEvent| {
        let input = e.target_unchecked_into::<HtmlInputElement>();
        let value = input.value().parse::<isize>().unwrap_or_default();
        value
    });
    let onwheel = if props.disabled {
        Callback::noop()
    } else {
        Callback::from({
            let oninput = props.oninput.clone();
            let min = props.min;
            let max = props.max;
            move |e: WheelEvent| {
                let input = e.target_unchecked_into::<HtmlInputElement>();
                let value = input.value().parse::<isize>().unwrap_or_default();
                log::info!("wheel {} {}", e.delta_x(), e.delta_y());
                let dy = e.delta_y();
                if dy > 0.0 {
                    oninput.emit((value + 1).clamp(min, max));
                } else if dy < 0.0 {
                    oninput.emit((value - 1).clamp(min, max));
                }
            }
        })
    };
    let style = format!("--value: {}%", (props.value - props.min) * 100 / props.max);
    let mut classes = classes!("slider");
    if props.disabled {
        classes.push("disabled");
    }
    html! {
        <div class={classes} {style}>
            <input type="range" disabled={props.disabled} min={props.min.to_string()} max={props.max.to_string()} value={props.value.to_string()} {oninput} {onwheel} />
        </div>
    }
}
